import fs from 'fs';
import path from 'path';

/**
 * 遍历文件夹.
 * @param dir
 * @param entries
 * @param callback
 * @returns {*[]}
 */
function traverseDir(dir,entries=[],callback) {
  const files = fs.readdirSync(dir);
  files.forEach(file => {
    const fullPath = path.join(dir, file);
    const stats = fs.statSync(fullPath);
    if (stats.isDirectory()) {
      // 如果是目录，则递归调用 traverseDir
      traverseDir(fullPath,  entries,callback);
    } else  {
      if(callback && callback(fullPath)){
        entries.push(fullPath);
      }
    }
  });
  return entries;
}

function readFile(path){
  let content="";
  try {
    content = fs.readFileSync(path, 'utf8');
  } catch (err) {
    console.error('读取文件时出错:', err);
  }
  return content;
}

function hasGlob(filePath){
  let content=readFile(filePath)
  if(content.indexOf("import.meta.glob")!=-1){
    return true;
  }
  return false;
}

//if(content.indexOf("import.meta.glob")!=-1)

function isVueJs(filePath){
  const fileExtension = path.extname(filePath);
  const extensionWithoutDot = fileExtension.slice(1);
  let extAry=['vue','js'];
  return  extAry.includes(extensionWithoutDot);
}

function myCallBack(path){
  let excludes=["uni_modules","Util.js","i18LangUtil.js","util.js"];
  for(let i=0;i<excludes.length;i++){
    if(path.includes(excludes[i])){
      return false;
    }
  }
  let isVue=isVueJs(path);
  if(!isVue){
    return false;
  }
  if(hasGlob(path)){
    return true;
  }
  return false;
}

export default function HelloWorldPlugin() {
  return {
    name: 'hello-world-plugin',
    buildStart() {
      let files=traverseDir(path.resolve( path.dirname(__dirname), 'src'),[],myCallBack);
      files.forEach(function(file) {
        console.log(file);
      });
      console.log('HelloWorldPlugin开始编译!');
    },
  };
}
